package com.settlement.system.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.settlement.system.common.constant.ExcelConstants;
import com.settlement.system.common.model.Option;
import com.settlement.system.common.result.PageResult;
import com.settlement.system.common.result.Result;
import com.settlement.system.listener.easyexcel.AuditConfigImportListener;
import com.settlement.system.listener.easyexcel.BillConfigImportListener;
import com.settlement.system.model.entity.SysAuditColumn;
import com.settlement.system.model.query.AuditColumnPageQuery;
import com.settlement.system.model.query.UserPageQuery;
import com.settlement.system.model.vo.AuditConfigImportVO;
import com.settlement.system.model.vo.BillConfigImportVO;
import com.settlement.system.model.vo.UserExportVO;
import com.settlement.system.service.SysAuditColumnService;
import com.settlement.system.service.SysDictService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 标准核销表字段对应关系 前端控制器
 * </p>
 *
 * @author huangrensen
 * @since 2023-08-07
 */
@Tag(name = "标准核销表字段对应关系")
@RestController
@RequestMapping("/api/v1/auditColumn")
@RequiredArgsConstructor
public class SysAuditColumnController {

    private final SysAuditColumnService auditColumnService;

    private final SysDictService dictService;

    @Operation(summary = "导入标准核销单配置表", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping("/_import")
    public Result<?> importTableConfig(@RequestParam("file") MultipartFile file) throws IOException {
        List<Option> list = dictService.listDictOptions("platform");
        List<ReadSheet> readSheets = EasyExcel.read(file.getInputStream()).build().excelExecutor().sheetList();
        for (ReadSheet readSheet : readSheets) {
            String sheetName = readSheet.getSheetName();
            Option option = list.stream().filter(dict -> dict.getLabel().equals(sheetName)).findFirst().orElse(null);
            if (option == null) {
                return Result.failed(String.format("没有配置到【%s】平台的字典下拉框选项", sheetName));
            }
        }
        for (ReadSheet readSheet : readSheets) {
            AuditConfigImportListener listener = new AuditConfigImportListener();
            String sheetName = readSheet.getSheetName();
            EasyExcelFactory.read(file.getInputStream(), AuditConfigImportVO.class, listener).sheet(sheetName).doRead();
            List<AuditConfigImportVO> rows = listener.getVos();
            // 保存数据
            auditColumnService.importConfig(rows, sheetName);
        }
        return Result.success("导入成功");
    }

    @Operation(summary = "核销报表导入模板下载", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/template")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        String fileName = "核销报表导入模板.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));

        String fileClassPath = ExcelConstants.EXCEL_TEMPLATE_DIR + File.separator + fileName;
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(fileClassPath);

        ServletOutputStream outputStream = response.getOutputStream();
        ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build();

        excelWriter.finish();
    }

    @Operation(summary = "核消报表配置列表", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/page")
    public PageResult<SysAuditColumn> getAuditColumnPage(@ParameterObject AuditColumnPageQuery queryParams) {
        Page<SysAuditColumn> result = auditColumnService.getAuditColumnPage(queryParams);
        return PageResult.success(result);
    }

    @Operation(summary = "导出标准核销表配置", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/_export")
    public void exportUsers(HttpServletResponse response) throws Exception {
        String fileName = "标准核销表配置.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
        List<SysAuditColumn> auditColumns = auditColumnService.getAll();
        Set<String> keySet;
        Map<String, List<SysAuditColumn>> groupMap;
        if (auditColumns.size() == 0) {
            // 兼容没有数据导出表格失败的情况
            keySet = new HashSet<>();
            keySet.add("淘宝");
            groupMap = new HashMap<>();
            groupMap.put("淘宝", new ArrayList<>());
        } else {
            // 按照平台分组
            groupMap = auditColumns.stream().collect(Collectors.groupingBy(SysAuditColumn::getPlatform));
            keySet = groupMap.keySet();
        }
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
        for (String platform : keySet) {
            WriteSheet writeSheet = EasyExcel.writerSheet(platform).head(AuditConfigImportVO.class).build();
            excelWriter.write(groupMap.get(platform), writeSheet);
        }
        excelWriter.finish();
    }
}
